import React from 'react';
import { connect } from 'react-redux';
import menuRoute from 'routes/menuRoute';
import moment from 'moment'
import {Form, Button, message, Spin, Modal, Icon} from 'antd';
import Chooser from 'components/chooser';
import InlineDescription from 'components/inline-description';

import baseService from 'share/base.service';
import chooserData from 'share/chooserData';
import corporatePaymentReportService from 'containers/corporate-payment-report/corporate-payment-report.service';
import customField from 'share/customField';
import { messages, deepFullCopy, deepCopy } from 'share/common';
import 'styles/corporate-payment-report/new-corporate-payment-report.scss';

import requestService from 'containers/request/request.service'
import errorMessage from "share/errorMessage"
import isJSON from 'is-json';
import debounce from 'lodash.debounce';
import SVGIcon from "components/SVGIcon";
import NewVendorForm from "../request/new-request/new-vendor-form";

const FormItem = Form.Item;
let isClearStatus = false;
let newExpenseReportThis;
let firstInitLoad;

class NewExpenseReport extends React.Component {
  constructor(props) {
    super(props);
    newExpenseReportThis = this;
    firstInitLoad = false;
    this.state = {
      loading: true,
      submitting: false,
      signEnable: false,
      formDetail: {},
      formDefaultValue: [], //表单默认值
      approvalAddSignScope: [], //加签人列表
      isMultiApplication: false, //是否可以关联多申请单
      requestParticipant: [], //关联申请单带入的参与人
      expenseReport: deepFullCopy(props.params.expenseReport), //单据内编辑单头时用到的 单据大对象,
      editReportFlag: !!props.params.expenseReport, //是否由编辑单据头打开
      isInitDefaultValue: false, //是否在初始化默认值，若为true，则不触发formItemChange方法，bug 32149
      contractParams: { // 获取合同的参数
        companyOID: props.company.companyOID,
        currency: props.company.baseCurrency
      },
      associationContract: {},
      jobInfo: props.params.jobInfo || {},
      newVendorVisible: false,
      formMaxHeight: 'calc(100vh -126px)',
      relatedApplicationProperty: {},
      showApplication: false,
      showContract: false,
      selectedCompanyOID: props.company.companyOID, //公司控件选择的公司
      selectDepartment: '',
      selectCompany: props.company.companyOID
    };
    this.unEditableField = ['select_approver', 'applicant', 'select_corporation_entity', 'venMaster',
      'venMasterSwitch', 'ying_fu_select_approver', 'payee', 'writeoff_flag', 'total_budget', 'employee_expand'];
    this.handleCostCenter = debounce(this.handleCostCenter, 300);
  }

  componentWillMount() {
    const { user } = this.props;
    const { formId, formDetail, userOID, applicantJobId, isAuditEditable } = this.props.params;
    isClearStatus = false;
    //审核编辑的时候不允许编辑自选审批人
    !isAuditEditable && this.isCounterSignEnable(formId || formDetail.formOID, applicantJobId);
    if (formId && userOID && userOID !== ':userOID' && userOID !== user.userOID) {
      this.dealProxies(userOID);
    } else {
      this.handleFormDetail();
    }
    //新建报销单时获取岗位信息
    this.getJobInfo();
  }

  componentDidMount () {
   // this.resetFormPageHeight();
  };

  resetFormPageHeight = () => {
    const { editReportFlag } = this.state;
    let formHeadHeight = document.querySelector('.new-corporate-payment-report-box .form-head')
      .getBoundingClientRect().height;
    this.setState({ formMaxHeight: `calc(100vh - ${(editReportFlag ? 50 : 66) + formHeadHeight}px)` });
  };

  //处理代理单据逻辑
  dealProxies(usersOID) {
    baseService.changeLoginInfo(usersOID).then(() => {
      this.handleFormDetail();
    }).catch(err => {
      location.href = '/';
      message.error(messages('common.error')/*哦呼，服务器出了点问题，请联系管理员或稍后再试:(*/);
    });
  };

  handleFormDetail = () => {
    const { params: { formId, formDetail } } = this.props;
    if (formDetail) {
      this.setState({ formDetail: formDetail, loading: false }, () => {
        this.initCustomFormProperty();
        setTimeout(this.resetFormPageHeight, 500);
      });
    } else {
      this.setState({ loading: true });
      baseService.getFormDetail(formId)
        .then(res => {
          this.setState({ formDetail: res.data }, () => {
            this.getFormDefaultValue();
            setTimeout(this.resetFormPageHeight, 500);
            this.initCustomFormProperty();
          });
        })
      this.checkRelatedApplication();
    }
  };

  initCustomFormProperty = () => {
    const { formDetail: { customFormPropertyMap } } = this.state;
    let relatedApplicationProperty = customFormPropertyMap &&
      JSON.parse(customFormPropertyMap['related.application.property'] || '{}');
    let showApplication = customFormPropertyMap && relatedApplicationProperty.enable;
    let showContract = this.getCustomFormPropertyValue('report.property.associated.contract.enabled', 'true');
    this.setState({ relatedApplicationProperty, showApplication, showContract });
  };

  handleRequestDetail = () => {
    const { params: { applicationOID } } = this.props;
    if (applicationOID && applicationOID !== ':applicationOID') { //申请单跳入报销单
      requestService.getRequestDetail(applicationOID)
        .then(res => {
          this.props.form.setFieldsValue({ 'application': [res.data] });
          this.handleChangeApplication([res.data]);
        })
        .catch(err => {
          errorMessage(err.response);
        });
    }
  };

  //获取表单默认值
  getFormDefaultValue = (userOID = this.props.user.userOID) => {
    const { params: { formId, applicantJobId }, company } = this.props;
    const { formDetail, expenseReport } = this.state;
    let { contractParams } = this.state;
    let jobId = applicantJobId === ':applicantJobId' ? undefined : applicantJobId;
    corporatePaymentReportService.getFormValue(userOID, formId, jobId).then(res => {
      let customFormFields = formDetail.customFormFields || [];
      if (expenseReport) {
        customFormFields = expenseReport.custFormValues || customFormFields;
      }
      contractParams.companyOID = company.companyOID;
      contractParams.currency = company.baseCurrency;
      customFormFields.forEach(field => {
        res.data.forEach(item => {
          if (field.messageKey === 'select_company' && item.fieldOID === field.fieldOID) {
            contractParams.companyOID = item.value;
          }
        });
      });
      this.setState({
        contractParams,
        loading: false,
        formDefaultValue: res.data
      })
    })
  };

  // 获取滚动元素相对元素对象
  getPopupContainer = () => {
    return this.refs.newCorporatePaymentReport;
  };

  //处理是否启用时间
  processEnableTime = (field) => {
    let enableTime = false;
    if (field.fieldConstraint && JSON.parse(field.fieldConstraint) && JSON.parse(field.fieldConstraint).enableTime) {
      enableTime = true;
    }
    return enableTime;
  };

  //处理启用时间默认值
  processDefaultTime = (field) => {
    let defaultTime = null;
    if (field.fieldConstraint && JSON.parse(field.fieldConstraint)) {
      if (JSON.parse(field.fieldConstraint).defaultTime) {
        defaultTime = moment(moment(JSON.parse(field.fieldConstraint).defaultTime).format('HH:mm'), 'HH:mm');
      } else {
        if (field.messageKey === 'start_date') {
          defaultTime = moment('00:00', 'HH:mm');
        }
        if (field.messageKey === 'end_date') {
          defaultTime = moment('23:59', 'HH:mm');
        }
      }
    }
    return defaultTime;
  };

  //获取岗位详情
  getJobInfo = () => {
    const { companyWithUserJobsDTOList } = this.props.user;
    const { applicantJobId } = this.props.params;
    let jobId = applicantJobId;
    // 处理详情没返回 applicantJobId 的情况
    if (
      !jobId &&
      companyWithUserJobsDTOList &&
      companyWithUserJobsDTOList[0] &&
      companyWithUserJobsDTOList[0].userJobsDTOList &&
      companyWithUserJobsDTOList[0].userJobsDTOList[0]
    ) {
      jobId = companyWithUserJobsDTOList[0].userJobsDTOList[0].id
    }
    jobId && corporatePaymentReportService.getJobInfo(jobId).then(res => {
      this.setState({ jobInfo: res.data || {} })
    })
  };

  filterByAuditEditRule = field => this.props.params.isAuditEditable ? this.unEditableField.indexOf(field.messageKey) === -1 : true;

  renderFormItem = () => {
    const { getFieldDecorator, getFieldsValue } = this.props.form;
    const { applicantJobId, isAuditEditable } = this.props.params;
    let { formDetail, formDefaultValue, expenseReport, jobInfo, selectCompany } = this.state;
    const { companyOID, departmentOID } = jobInfo;
    let customFormFields = deepFullCopy(formDetail.customFormFields || []);
    const messageKeys = [
      ['input', { max: 200 }],
      ['title', { max: 500 }],
      ['text_area', { max: 1000 }],
      ['employee_expand', { max: 200 }],
      ['remark', { max: 200 }],
      ['destination', {}]
    ];
    const map = new Map(messageKeys);
    const validator = (item, value, callback, name) => {
      if (value && !value.trim()) {
        callback(messages('common.name.is.required', { arg1: name }));
      }
      callback();
    };
    let openModal;
    if (expenseReport) {
      customFormFields = deepFullCopy(expenseReport.custFormValues || customFormFields);
      formDetail.customFormFields = customFormFields;
    }
    customFormFields.length > 0 && customFormFields.sort((a, b) => a.sequence > b.sequence || -1);
    return customFormFields.filter(this.filterByAuditEditRule).map(field => {
      if (field.messageKey === 'select_participant' && field.hide) {
        return;
      }
      let switchMessageKey = ['switch', 'writeoff_flag'];
      let option = {
        valuePropName: ~switchMessageKey.indexOf(field.messageKey) ? 'checked' : 'value',
        rules: []
      };
      let fieldNameHelp = '';
      //表单默认值
      let fieldDefaultValue = {};
      formDefaultValue.map(item => {
        item.fieldOID === field.fieldOID && (fieldDefaultValue = item)
      });
      if (expenseReport) {
        option.initialValue = customField.getInitialValue(field, expenseReport);
      } else {
        option.initialValue = customField.getDefaultValue(field, fieldDefaultValue)
      }
      //开始结束日期以组合组件range_picker显示
      if (field.messageKey === 'start_date') {
        //开始结束日期都有值时，该组件才有值
        let firstName = field.fieldName, endName = '', startValue = field.value;
        customFormFields.map(fieldItem => {
          if (fieldItem.messageKey === 'end_date') {
            endName = fieldItem.fieldName;
            if (startValue && fieldItem.value) {
              option.initialValue = [
                customField.getInitialValue(field, expenseReport),
                customField.getInitialValue(fieldItem, expenseReport)
              ]
            }
          }
        });
        //开始结束日期都启用时间时，该组件才启用时间
        if (this.processEnableTime(field)) {
          field.defaultValueTime = [];
          field.defaultValueTime.push(this.processDefaultTime(field));
          customFormFields.map(fieldItem => {
            if (fieldItem.messageKey === 'end_date' && this.processEnableTime(fieldItem)) {
              field.defaultValueTime.push(this.processDefaultTime(fieldItem));
              field.enableTime = true
            }
          })
        }
        field.messageKey = 'range_picker';
        field.fieldName = firstName + '-' + endName;
        field.promptInfoList = [firstName, endName];
      }
      if (field.required) {
        option.rules.push({
          required: field.required,
          message: messages('common.name.is.required', {arg1: field.fieldName})  //${field.fieldName}必填
        });
        if (map.has(field.messageKey)) {
          option.rules.push(
            {
              validator: (item, value, callback) => validator(item, value, callback, field.fieldName)
            }
          );
        }
      }

      if (map.has(field.messageKey)) {
        if (field.messageKey === 'employee_expand') {
          if (!(field.fieldContent && (JSON.parse(field.fieldContent) || {}).messageKey === 'cust_list')) {
            option.rules.push(
              {
                max: map.get(field.messageKey),
                message: messages('common.max.characters.length', { max: map.get(field.messageKey).max })
              });
          }
        } else {
          let configMax = field.fieldContent && JSON.parse(field.fieldContent).maxLength;
          let maxLength = configMax || map.get(field.messageKey).max;
          maxLength && option.rules.push({
            max: +maxLength,
            message: messages('common.max.characters.length', { max: maxLength })
          })
        }
      }
      //编辑模式不能修改申请人、供应商、公司、币种、部门
      if (expenseReport &&
        (field.messageKey === 'applicant' || field.messageKey === 'vendor_setting' ||
          field.messageKey === 'select_company' || field.messageKey === 'currency_code' ||
          field.messageKey === 'select_department')
      ) {
        field.isReadOnly = true;
      }
      if (field.messageKey === 'number') {
        if (field.fieldContent && JSON.parse(field.fieldContent)) {
          let fieldContentObject = JSON.parse(field.fieldContent);
          fieldNameHelp = fieldContentObject.unit ? `(${fieldContentObject.unit})` : '';
        }
      }
      let selectParticipantVisible = true;
      if (field.messageKey === 'select_participant' && field.fieldContent) {
        selectParticipantVisible = JSON.parse(field.fieldContent).isUse;
      }
      if(field.messageKey === 'vendor_setting') {
        openModal = () => this.setState({ newVendorVisible: true});
      }
      let label = `${field.fieldName}${fieldNameHelp}`;
      return (
        field.fieldOID &&
        field.messageKey !== 'ying_fu_select_approver' &&
        selectParticipantVisible &&
        field.messageKey !== 'end_date' &&
        !field.hide
      ) && (
        <FormItem label={label || ' '} key={field.fieldOID} colon={!!label} {...this.formItemLayout}>
          {getFieldDecorator(field.fieldOID, option)(
            customField.renderForm({
              field,
              fieldDefaultValue,
              formDetail,
              copyValue: null,
              formValues: getFieldsValue(),
              type: 2,
              getPopupContainer: this.getPopupContainer,
              propsParams: {
                companyOID,
                departmentOID,
                isAuditEditable,
                entityDetail: expenseReport,
                openModal,
                selectedCompanyOID: selectCompany,
                corporateFlag: true,
                getModalRef: ref => this.modalRef = ref
              },
              jobId: applicantJobId,
              jobInfo,
              form: this.props.form
            })
          )}
        </FormItem>
      )
    })
  };

  //切换了公司.或者切换部门都要查询是否要清空成本中心。
  handleCostCenter = async ({ selectDepartment, selectCompany }) => {
    let { params: { expenseReport, userOID }, form: { getFieldValue, setFieldsValue } } = this.props;
    let { formDetail: { customFormFields }, jobInfo: { companyOID, departmentOID } } = this.state;

    if (expenseReport) {
      customFormFields = expenseReport.custFormValues;
      userOID = expenseReport.applicantOID;
    }

    const params = {
      userOID,
      departmentOID,
      companyOID,
      costCenterItemOIDs: []
    };

    customFormFields.forEach(i => {

      // 如果处于财务编辑 公司字段会隐藏不可使用getFieldValue去获取值，
      // 因为未在表单注册，使用getFieldValue则会赋值当前属性值undefined
      if (!this.filterByAuditEditRule(i)) {
        if (i.messageKey === 'select_company') {
          params.companyOID = i.value || companyOID;
        }
        return;
      }

      if (i.messageKey === 'select_cost_center' && !i.isReadOnly) {
        let preCostCenter = getFieldValue(i.fieldOID);
        if (Object.prototype.toString.call(preCostCenter) === '[object Array]') {
          preCostCenter = preCostCenter.costCenterItemOID;
        }
        preCostCenter && params.costCenterItemOIDs.push(preCostCenter);
      }

      if (i.messageKey === 'select_company') {
        let preCompany = getFieldValue(i.fieldOID);
        if (Object.prototype.toString.call(preCompany) === '[object Object]') {
          preCompany = preCompany.key;
        }
        if (Object.prototype.toString.call(selectCompany) === '[object Object]') {
          selectCompany = selectCompany.key;
        }
        params.companyOID = selectCompany || preCompany || companyOID;
      }

      if (i.messageKey === 'select_department') {
        params.departmentOID = selectDepartment || getFieldValue(i.fieldOID) || departmentOID;
      }
    });

    if(!params.costCenterItemOIDs[0]){
      return ;
    }
    this.setState({ loading: true });
    try {
      const ret = await baseService.checkCostCenterNeedEmpty(params);
      customFormFields.forEach(i => {
        if (i.messageKey === 'select_cost_center' && !i.isReadOnly && !!getFieldValue(i.fieldOID) && !ret.data[getFieldValue(i.fieldOID)]) {
          setFieldsValue({ [i.fieldOID]: '' });
        }
      });
    }
    catch (e) {
      e && e.response ? errorMessage(e.response) : '';
    }
    this.setState({ loading: false });
  };

  //控件之间联动关系
  formItemChange = (value) => {
    const { enableDepCompany, form: { getFieldValue, setFieldsValue } } = this.props;
    let { formDetail, isInitDefaultValue,  contractParams, associationContract, editReportFlag } = this.state;
    const { companyOID, baseCurrency } = this.props.company;
    if (isInitDefaultValue) return;
    let customFormFields = formDetail.customFormFields || [];
    if (!(value && Object.prototype.toString.call(value) === '[object Object]')) return;
    customFormFields.map(item => {
      if (item.fieldOID in value) {
        if (item.messageKey === 'select_department') {
          this.setState({ selectDepartment: value[item.fieldOID] });
          this.handleCostCenter({ selectDepartment: value[item.fieldOID] });
        }
        //参与人部门权限控件
        if ((item.messageKey === 'select_department' || item.messageKey === 'select_cost_center')) {
          item.value = value[item.fieldOID];
          customFormFields.map(i => {
            if (i.messageKey === 'select_participant') {
              setTimeout(() => {
                firstInitLoad = true;
              }, 200);
              if (firstInitLoad) {
                i.clearDefault = true;
              }
              let fieldContent = i.fieldContent ? JSON.parse(i.fieldContent) : {editable: true};
              if (!i.isReadOnly && fieldContent.editable) {
                this.props.form.resetFields(i.fieldOID);
              }
            }
          });
        }
        //选择公司
        if (item.messageKey === 'select_company') {
          customFormFields.map(i => {
            if (i.messageKey === 'select_department' && getFieldValue(i.fieldOID) && value[item.fieldOID]) {
              baseService.checkDepartmentNeedEmpty({
                companyOID: value[item.fieldOID],
                departmentOID: getFieldValue(i.fieldOID)
              }).then(res => {
                if (res.data && res.data.association === 'Y') {
                  this.handleCostCenter({selectCompany: value[item.fieldOID], selectDepartment: getFieldValue(i.fieldOID)});
                } else {
                  setFieldsValue({[i.fieldOID]: undefined});
                  this.handleCostCenter({selectCompany: value[item.fieldOID], selectDepartment: undefined});
                }
              });
            } else {
              this.handleCostCenter({ selectCompany: value[item.fieldOID] });
            }
          });

          let vendorField = customFormFields.filter(i => i.messageKey === 'vendor_setting')[0].fieldOID;
          let contractFieldValue = this.props.form.getFieldValue('contract');
          if(getFieldValue(vendorField) && !this.isSelectContractingCompany && !editReportFlag) {
            this.props.form.setFieldsValue({[vendorField]: undefined});
          }

          contractParams.companyOID = typeof value[item.fieldOID] === 'string' ? value[item.fieldOID] :
            (value[item.fieldOID] ? value[item.fieldOID].companyOID : companyOID);
          if (contractFieldValue && contractFieldValue[0] &&
            associationContract.companyOID !== value[item.fieldOID] &&
            !this.isSelectContractingCompany
          ) {
            message.warning(messages('finance-9.key70')/*所选公司与关联的合同公司必须一致！*/);
            this.handleClearContract();
          }

          let venMasterField = customFormFields.filter(i => i.messageKey === 'venMaster');
          if(venMasterField.length) {
            this.props.form.setFieldsValue({[venMasterField[0].fieldOID]: undefined});
          }
          this.isSelectContractingCompany = false;
          this.setState({ selectCompany: contractParams.companyOID });
        }
        //收款人银行关联控件
        if (item.messageKey === 'payee' && value[item.fieldOID] && typeof value[item.fieldOID] === 'object') {
          item.value = value[item.fieldOID]['key'];
          customFormFields.map(i => {
            if (i.messageKey === 'contact_bank_account') {
              let param = {
                userOID: value[item.fieldOID]['key'],
                page: 0,
                size: 20
              };
              let bank = { [i.fieldOID]: undefined };
              baseService.getUserBanks(param).then(res => {
                let data = res.data;
                if (data && data.length > 0) {
                  data.map(item => {
                    if (item.isPrimary || data.length === 1) { // 银行卡的长度为1则也默认
                      bank = {
                        [i.fieldOID]: [{
                          bankAccountNo: item.bankAccountNo,
                          originalBankAccountNo: item.originalBankAccountNo,
                          contactBankAccountOID: item.contactBankAccountOID
                        }]
                      };
                    }
                  })
                }
                this.props.form.setFieldsValue(bank);
              }).catch(e => {
                this.props.form.setFieldsValue(bank);
              })
            }
          });
        }
        if (item.messageKey === 'select_cost_center') {
          if (item.dataSource && JSON.parse(item.dataSource || '{}').type === 'father') { //父成本中心
            customFormFields.map(i => {
              //父成本中心修改时，子成本中心置空
              if (i.messageKey === 'select_cost_center' && i.dataSource && JSON.parse(i.dataSource || '{}').type === 'son') {
                this.props.form.setFieldsValue({ [i.fieldOID]: undefined });
              }
            });
          }
        }
        if (item.messageKey === 'currency_code') {
          contractParams.currency = value[item.fieldOID] || baseCurrency;
          this.setState({ contractParams });
          if(this.props.form.getFieldValue('contract') && associationContract.contractCurrency !== value[item.fieldOID]){
            message.warning(messages('finance-9.key71')/*所选币种与关联的合同币种必须一致！*/);
            this.handleClearContract();
          }
        }
        if (item.messageKey === 'vendor_setting') {
          if(this.props.form.getFieldValue('contract') && associationContract.partnerId !== value[item.fieldOID] &&
            !this.isSelectContractingVendor
          ){
            message.warning(messages('finance-9.key105')/*所选供应商与关联合同的合同方必须一致！*/);
            this.handleClearContract();
          }
          this.isSelectContractingVendor = false;
        }
      }
    });
  };

  //提交前检查组合控件的表单值验证,异步方法
  submitSaveValidateCombinationForm = () => {
    let { formDetail } = this.state;
    let customFormFields = formDetail.customFormFields || [];
    let isHaveValidate = false;
    let needValidateForms = ['venMasterSwitch', 'linkage_switch'];
    customFormFields.map(item => {
      if (~needValidateForms.indexOf(item.messageKey)) {
        let info = this.props.form.getFieldValue(item.fieldOID);
        if (info) {
          info.callBackSubmit = !info.callBackSubmit;
          this.props.form.setFieldsValue({ [item.fieldOID]: info });
          isHaveValidate = true;
        }
      }
      if(item.messageKey === 'select_company') {

      }
    });
    return isHaveValidate;
  };

  //组合表单验证结果
  combinationFormValidateResult = () => {
    let { formDetail } = this.state;
    let customFormFields = formDetail.customFormFields || [];
    let isPassValid = true;
    let needValidateForms = ['venMasterSwitch', 'linkage_switch'];
    customFormFields.map(item => {
      if (~needValidateForms.indexOf(item.messageKey)) {
        let info = this.props.form.getFieldValue(item.fieldOID);
        if (info) {
          isPassValid = isPassValid && info.isPassValid;
        }
      }
    });
    return isPassValid;
  };

  handleSave = (e) => {
    e.preventDefault();
    if (this.submitSaveValidateCombinationForm()) {
      //组合子表单验证信息传递需要时间
      setTimeout(this.delayHandleSave, 10)
    } else {
      this.delayHandleSave();
    }
  };

  /**
   * 格式化时间为UTC格式(YYYY-MM-DDTHH:mm:ssZ)
   * @param date: string(YYYY-MM-DD HH:mm:ss)
   * @returns {string}
   */
  formatDateToUtc = (date) => {
    return moment(date).utc().format('YYYY-MM-DDTHH:mm:ss') + 'Z'
  };

  //判断是否需要重新计算补贴
  checkSubsidyChange = () => {
    return new Promise((resolve) => {
      this.setState({ submitting: true });
      let { expenseReport } = this.state;
      const { getFieldValue } = this.props.form;
      let dateFieldOID = null, startDate = null, endDate = null;
      //新建报销单
      if (!expenseReport) {
        resolve(false);
        return
      }
      (expenseReport.custFormValues || []).map(item => {
        if (item.messageKey === "start_date") {
          dateFieldOID = item.fieldOID;
        }
      });
      if (dateFieldOID && getFieldValue(dateFieldOID) && getFieldValue(dateFieldOID)[0]) {
        startDate = getFieldValue(dateFieldOID)[0].format('YYYY-MM-DD HH:mm:ss');
        endDate = getFieldValue(dateFieldOID)[1].format('YYYY-MM-DD HH:mm:ss');
      }
      if (startDate && endDate) {
        let params = {
          expenseReportOID: expenseReport.expenseReportOID,
          startDate: this.formatDateToUtc(startDate),
          endDate: this.formatDateToUtc(endDate)
        };
        if (expenseReport.recalculateSubsidy) {
          resolve(false)
        } else {
          corporatePaymentReportService.checkSubsidyChange(params).then(res => {
            if (res.data) {
              Modal.confirm({
                title: messages('finance-9.key72')/*修改后，补贴费用将重新生成，是否继续*/,
                onOk: () => {
                  expenseReport.recalculateSubsidy = true;
                  this.setState({ expenseReport }, this.delayHandleSave)
                },
                onCancel: () => this.setState({ submitting: false })
              })
            }
            resolve(res.data)
          }).catch(() => {
            resolve(false)
          })
        }
      } else {
        expenseReport.recalculateSubsidy = false;
        this.setState({ expenseReport });
        resolve(false)
      }
    })
  };

  delayHandleSave = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!this.combinationFormValidateResult()) {
        return;
      }
      const { applicantJobId, isAuditEditable } = this.props.params;
      let { formDetail, expenseReport, isMultiApplication } = this.state;
      let target = JSON.parse(JSON.stringify(expenseReport || formDetail));
      target.currencySame = this.checkFunctionProfiles('web.invoice.keep.consistent.with.expense', [true]);
      applicantJobId && applicantJobId !== ":applicantJobId" && (target.applicantJobId = applicantJobId);
      if (values.application) {
        target.applicationOID = values.application[0].applicationOID;
        if (isMultiApplication) { //关联多申请单
          let expenseReportApplicationDTOS = [];
          values.application.map(item => {
            expenseReportApplicationDTOS.push({
              applicationOID: item.applicationOID,
              tenantId: this.props.tenant.id
            })
          });
          target.expenseReportApplicationDTOS = expenseReportApplicationDTOS;
        }
      }

      if(values.contract && values.contract[0]) {
        target.contractHeaderId = values.contract[0].contractHeaderId;
      }
      let customFormFields = deepFullCopy(formDetail.customFormFields || []);
      if (expenseReport) {
        customFormFields = deepFullCopy(expenseReport.custFormValues || []);
      } else {
        target.remark = null;
      }
      if (!err) {
        const { expenseReportInvoices, formId, userOID } = this.props.params;
        let custFormValues = [];
        let canSubmit = true;
        Object.keys(values).map(key => {
          customFormFields.filter(this.filterByAuditEditRule).map(field => {
            if (key === field.fieldOID) {
              custFormValues.push(customField.formatFormValue(field, values[key]));
            }
          })
        });
        target.countersignApproverOIDs = this.props.form.getFieldsValue().addSign;
        target.custFormValues = custFormValues;
        if (formId && userOID && userOID !== ':userOID') {
          target.applicantOID = userOID;
        }

        //fixed 45097
        //成本中心24的值 没有走以下这个遍历  原因是遍历的时候更改了原数组
        target.custFormValues.map((item, index) => {
          if (item.messageKey === "select_cost_center") {
            try {
              item.value = isJSON(item.value) ? JSON.parse(item.value)[0].costCenterItemOID : (typeof item.value === 'string' ? item.value : item.value[0].costCenterItemOID);
            } catch(e) {}
          }
          if (item.messageKey === "select_participant" && item.value) {
            let itemValue = JSON.parse(item.value);
            itemValue.map(user => {
              this.state.requestParticipant.map(requestUser => {
                if (user.userOID === requestUser.userOID) {
                  user.highOff = true
                }
              })
            });
            item.value = JSON.stringify(itemValue)
          }
          // 计算公式额外校验
          if (item.messageKey === 'calculate_formula' && item.value && item.value.split('.')[0].length >= 16) {
            message.error(messages('finance-9.key73',{arg1: item.fieldName})/*{arg1}最多支持15位数字*/);
            canSubmit = false;
          }
        });
        target.custFormValues.map((item, index) => {
          //保存前要将连选日期控件range_picker分为开始日期／结束日期控件
          if (item.messageKey === "start_date") {
            customFormFields.map(fieldItem => {
              if (fieldItem.messageKey === "end_date") {
                let endDateItem = fieldItem;
                if (item.value) {
                  let rangePickerValue = deepFullCopy(item.value);
                  if (this.processEnableTime(item) && this.processEnableTime(fieldItem)) {
                    item.value = this.formatDateToUtc(rangePickerValue[0]);
                    endDateItem.value = this.formatDateToUtc(rangePickerValue[1]);
                  } else {
                    item.value = this.formatDateToUtc(moment(rangePickerValue[0]).format("YYYY-MM-DD 00:00:00"));
                    endDateItem.value = this.formatDateToUtc(moment(rangePickerValue[1]).format("YYYY-MM-DD 23:59:59"));
                  }
                }
                if (!item.value) {
                  item.value = undefined;
                  endDateItem.value = undefined;
                }
                target.custFormValues.splice(index + 1, 0, endDateItem)
              }
            })
          }
        });
        if (formDetail.customFormPropertyMap['report.property.associated.contract.enabled'] === 'true') {
          target.contractPosition = formDetail.customFormPropertyMap['report.property.associated.contract.config'];
        }
        target.expenseReportInvoices = expenseReportInvoices || [];
        if (Array.isArray(target.countersignApproverOIDs)) {
          let approverOIDs = [];
          target.countersignApproverOIDs.map(item => approverOIDs.push(item.userOID || item));
          target.countersignApproverOIDs = approverOIDs;
        }
        if (!canSubmit) return;
        //保存前需要先判断是否需要显示重新计算补贴的提示框
        this.checkSubsidyChange().then(res => {
          if (!res) { //不需要弹框，可以直接保存
            this.setState({ submitting: true });
            //新建报销单的recalculateSubsidy要置为true
            !expenseReport && (target.recalculateSubsidy = true);
            let saveFunc = isAuditEditable ? 'saveAuditEdit' : 'saveExpenseReport';
            target.corporateFlag = true;
            let params = isAuditEditable ? {
              entityOID: expenseReport.expenseReportOID,
              entityType: 1002,
              recalculateSubsidy: target.recalculateSubsidy,
              customFormValueDTOs: JSON.parse(JSON.stringify(target.custFormValues)),
              corporateFlag: true
            } : target;
            corporatePaymentReportService[saveFunc](params).then(res => {
              this.setState({ submitting: false });
              message.success(res.data.draftToast || messages('common.save.success', {arg1: ''}));
              if(!isAuditEditable) {
                setTimeout(()=> {
                  message.success(messages('finance-9.key74')/*单据已保存*/);
                }, 3500);
              }
              if (expenseReport) {
                this.props.close({refresh: true, refreshAccount: !!res.data.draftToast});
              } else {
                let url = (
                  menuRoute.getRouteItem('corporate-payment-report-detail').url
                    .replace(':expenseReportOID', res.data.expenseReportOID)
                    .replace(':entry', 'my')
                );
                this.context.router.push(url);
              }
            }).catch(error => {
              this.setState({ submitting: false });
              message.error(error.response.data.message);
            })
          }
        });
      }
    })
  };

  //是否可以审批加签
  isCounterSignEnable = (formOID) => {
    corporatePaymentReportService.isCounterSignEnable(this.props.company.companyOID, formOID, 'enableAddSignForSubmitter').then(res => {
      this.setState({
        signEnable: res.data.enabled,
        approvalAddSignScope: res.data.approvalAddSignScope.companyOIDs
      })
    })
  };

  //修改关联申请单
  handleChangeApplication = (result) => {
    const { options } = this.props;
    const { applicantJobId } = this.props.params;
    const { formDetail, formDefaultValue, expenseReport } = this.state;
    this.setState({ loading:true });
    //处理申请单自定义表单值带入报销单自定义表单值
    if (result && result.length > 0) {
      let applicationOIDs = [];
      result.map(item => applicationOIDs.push(item.applicationOID));
      //需求12562 报销单创建时，可以关联多申请单
      let jobId = applicantJobId === ':applicantJobId' ? undefined : applicantJobId;
      corporatePaymentReportService.getMultiApplicationInfo(applicationOIDs, jobId, formDetail.formOID).then(res => {
        this.setState({ loading: false, isInitDefaultValue: true });
        let applicationFieldDefaultValues = res.data || [];
        let customFormFields = deepFullCopy(formDetail.customFormFields || []);
        //有默认值且当前选择的是默认值时，不带入关联申请单控件值的控件
        let hasDefaultNotChange = ['select_corporation_entity', 'select_company', 'select_department'];
        customFormFields.map(field => {
          applicationFieldDefaultValues.map(item => {
            let { getFieldsValue, getFieldValue } = this.props.form;
            let value = '';
            let fieldDefaultValue = undefined;
            if (getFieldsValue().hasOwnProperty(field.fieldOID)) {
              value = getFieldValue(field.fieldOID);
            }
            if (field.messageKey === "start_date") {
              field.messageKey = 'range_picker'
            }
            if (item.messageKey === "start_date") {
              applicationFieldDefaultValues.map(subItem => {
                if (subItem.messageKey === "end_date") {
                  item.messageKey = 'range_picker';
                  item.showValue = [moment(item.value), moment(subItem.value)];
                }
              })
            }
            formDefaultValue.map(formItem => {
              formItem.fieldOID === field.fieldOID && (fieldDefaultValue = customField.getDefaultValue(field, formItem))
            });
            if (
              item.messageKey === field.messageKey &&
              value !== item.value &&
              field.fieldOID === item.fieldOID &&
              item.messageKey !== 'end_date'
            ) {
              let setValue = (valueItem) => {
                let applicationDefaultCustom = valueItem;
                applicationDefaultCustom.name = applicationDefaultCustom.showValue;
                applicationDefaultCustom.fieldConstraint = field.fieldConstraint;
                applicationDefaultCustom.fieldContent = field.fieldContent;
                let defaultValue =
                  customField.getDefaultValue(field, applicationDefaultCustom) ||
                  customField.getInitialValue(applicationDefaultCustom, expenseReport);
                if (field.messageKey === 'more_cust_list') {
                  defaultValue = customField.getInitialValue(applicationDefaultCustom, expenseReport);
                }
                if (field.messageKey === "select_department") { //fix bug 26352
                  defaultValue = [{
                    [options['department']['fullPathDisabled'] === 'true' ? 'name' : 'path']: applicationDefaultCustom.name,
                    departmentOid: applicationDefaultCustom.value
                  }]
                }
                if (field.messageKey === "select_company") { //若公司组件的noDefault为true，customField.getDefaultValue()返回undefined
                  let fieldConstraint = JSON.parse(field.fieldConstraint || '{}');
                  fieldConstraint.noDefault = false;
                  field.fieldConstraint = JSON.stringify(fieldConstraint);
                  defaultValue = customField.getDefaultValue(field, applicationDefaultCustom);
                }
                defaultValue && this.props.form.setFieldsValue({[field.fieldOID]: defaultValue})
              };
              if (field.messageKey === 'select_participant') {
                this.setState({ requestParticipant: JSON.parse(item.value || '[]') })
              }
              if (~hasDefaultNotChange.indexOf(field.messageKey) && fieldDefaultValue && value) { //有默认值且当前选择的是默认值时，不带入关联申请单控件值
                if (
                  (field.messageKey === 'select_corporation_entity' && fieldDefaultValue[0] && value !== fieldDefaultValue[0].companyReceiptedOID) ||
                  (field.messageKey === 'select_department' && fieldDefaultValue[0] && value !== fieldDefaultValue[0].departmentOid) ||
                  (field.messageKey === 'select_company' && value !== fieldDefaultValue.key && value.key !== fieldDefaultValue.key)
                ) {
                  setValue(item)
                }
              } else {
                setValue(item)
              }
            }
          })
        });
        setTimeout(() => this.setState({ isInitDefaultValue: false }), 500)
      }).catch(err => {
        this.setState({ loading: false })
      });
    } else {
      this.setState({ loading: false })
    }
  };

  handleChangeContract = (contract) => {
    const { contractParams, formDetail, editReportFlag } = this.state;
    const { setFieldsValue } = this.props.form;
    if(editReportFlag) return;
    let customFormFields = deepFullCopy(formDetail.customFormFields || []);
    let vendorField = customFormFields.filter(i => i.messageKey === 'vendor_setting')[0].fieldOID;
    let companyField = customFormFields.filter(i => i.messageKey === 'select_company')[0].fieldOID;

    this.isSelectContractingCompany = true;
    this.isSelectContractingVendor = true;
    this.setState({
      associationContract: { ...contract[0], ...contractParams },
      }, () => {
      setFieldsValue({
        [companyField]:
          contract[0] ?
          {
            key: contract[0].companyOID,
            companyOID: contract[0].companyOID,
            name: contract[0].companyName,
            companyCode: contract[0].companyCode
          } : null,
        [vendorField]: contract[0] ? [{id: contract[0].partnerId, venNickname: contract[0].partnerName}] : null
      });
    });
  };

  handleClearContract = () => {
    this.props.form.setFieldsValue({ ['contract']: void 0 });
    this.setState({ associationContract: {} });
  };

  //查询报销单是否可关联多申请单
  checkRelatedApplication = () => {
    corporatePaymentReportService.checkRelatedApplication(this.props.params.formId).then(res => {
      this.setState({ isMultiApplication: res.data }, this.handleRequestDetail);
    })
  };

  //返回
  goBack = () => {
    let expenseReport = this.props.params.expenseReport;
    if (expenseReport) {
      this.props.close();
    } else {
      menuRoute.goBack(this)
    }
  };

  getCustomFormPropertyValue = (key, value) => {
    const { formDetail: { customFormPropertyMap } } = this.state;
    return customFormPropertyMap && (customFormPropertyMap[key] === value);
  };

  handleCancelNewVendor = () => this.setState({ newVendorVisible: false, chooseInfo:{} });

  // 新增供应商操作
  handleNewVendorOk = () => {
    this.modalRef && this.modalRef.getList();
    this.setState({
      newVendorVisible: false,
    })
  };

  renderDescriptionInline = () => {
    const { formDetail: { customFormPropertyMap }, editReportFlag } = this.state;
    const { language: { code } } = this.props;
    if(customFormPropertyMap && customFormPropertyMap['form.description']) {
      let instructions = JSON.parse(customFormPropertyMap['form.description']);
      if(instructions && instructions.enable) {
        let title = instructions[code] ? instructions[code].title : '';
        let content = instructions[code] ? instructions[code].content : '';
        return editReportFlag ?
          <div className="form-description">{customField.instructionsTag(customFormPropertyMap)}</div> :
          <InlineDescription title={title} content={content}/>
      }
    }
  };

  renderAssociateModule = () => {
    const { editReportFlag, formDetail: { customFormPropertyMap, formOID }, isMultiApplication, contractParams,
      relatedApplicationProperty, showApplication, showContract, selectDepartment, selectCompany
    } = this.state;
    const { loginUser: { userOID, departmentOID, companyOID }, expenseReport } = this.props;
    const { applicationOID, formId } = this.props.params;
    const { getFieldDecorator } = this.props.form;
    let applicationExtraParams = {};

    //关联申请单范围，1001-同申请人，1002-同部门，1003-同公司
    relatedApplicationProperty.relatedApplicationScope === 1001 &&
      (applicationExtraParams.expenseReportApplicantOID = userOID);
    relatedApplicationProperty.relatedApplicationScope === 1002 &&
    (applicationExtraParams.expenseReportDepartmentOID = selectDepartment || departmentOID);
    relatedApplicationProperty.relatedApplicationScope === 1003 &&
    (applicationExtraParams.expenseReportCompanyOID = selectCompany || companyOID);
    return (showApplication || showContract) &&
      <div className='form-module'>
        <h3 className='form-title'><SVGIcon className="form-title-icon" type="associate"/>{messages('finance-9.key75')/*关联信息*/}</h3>
        {showApplication &&
          <FormItem label={messages('finance-9.key76')/*关联申请单*/} {...this.formItemLayout}>
            {getFieldDecorator('application', {
              initialValue: expenseReport && expenseReport.expenseReportApplicationDTOS[0] ?
                [{businessCode: expenseReport.expenseReportApplicationDTOS[0].applicationBusinessCode}] :
                null,
              rules: [{
                required: JSON.parse(customFormPropertyMap['related.application.property']).required,
                message: messages('common.name.is.required', {arg1: messages('finance-9.key76')/*关联申请单*/})
              }]
            })(
              <Chooser
                type="available_corporate_request"
                listExtraParams={{
                  formOID: formId || formOID,
                  ...applicationExtraParams
                }}
                labelKey="businessCode"
                valueKey="applicationOID"
                disabled={(applicationOID !== ':applicationOID' && !!applicationOID) || editReportFlag}
                itemMap
                single={!isMultiApplication} //需求12562 报销单创建时，可以关联多申请单
                onChange={this.handleChangeApplication}
              />
            )}
          </FormItem>
        }
        {showContract &&
          <FormItem label={messages('finance-9.key23')/*关联合同*/} {...this.formItemLayout}>
            {getFieldDecorator('contract', {
              initialValue: expenseReport && expenseReport.contractNumber ? [{contractNumber: expenseReport.contractNumber}] : null,
              rules: [{
                required: this.getCustomFormPropertyValue('associate.contract.required', 'true'),
                message: messages('common.name.is.required', { arg1: messages('finance-9.key23')/*关联合同*/})
              }]
            })(
              <Chooser
                type="contract"
                listExtraParams={{
                  documentType: 'PUBLIC_REPORT',
                  applicantDepartmentOID: departmentOID,
                  corporateFlag: true,
                  ...contractParams
                }}
                labelKey="contractNumber"
                valueKey="contractHeaderId"
                itemMap
                onChange={this.handleChangeContract}
                single={true}
                disabled={editReportFlag}
              />
            )}
          </FormItem>
        }
      </div>
  };

  renderApproverModule = () => {
    const { signEnable, formDetail, expenseReport, approvalAddSignScope } = this.state;
    const { getFieldDecorator } = this.props.form;
    let signPerson = [];
    expenseReport && expenseReport.countersignApproverNames && expenseReport.countersignApproverNames.map(item => {
      signPerson.push({ userOID: item.userOID, fullName: item.fullName });
    });
    let companyDTOS = approvalAddSignScope.length ? approvalAddSignScope : null;
    let signName = customField.getSignNameForSubmitter(formDetail && formDetail.customFormPropertyMap);
    return signEnable && (
      <div className='form-module'>
        <h3 className='form-title'><SVGIcon className="form-title-icon" type="approve-info"/>{messages('finance-9.key77')/*审批信息*/}</h3>
        <FormItem label={signName} key="addSign" {...this.formItemLayout}>
          {getFieldDecorator('addSign', {
            rules: [{
              required: this.getCustomFormPropertyValue('enableCounterSignForSubmitterMustWriter', 'true'),
              message: messages('common.can.not.be.empty', {arg1: signName})
            }],
            initialValue: signPerson
          })(
            <Chooser
              selectorItem={function () {
                let chooserItemUser = deepFullCopy(chooserData['user']);
                chooserItemUser.title = signName;
                return chooserItemUser;
              }(this)}
              valueKey="userOID"
              labelKey="fullName"
              onlyNeed="userOID"
              maxNum={26}
              listExtraParams={{corporationOID: companyDTOS, roleType: 'TENANT', companyOID: companyDTOS}}
              showArrow={formDetail.customFormPropertyMap && formDetail.customFormPropertyMap.countersignType === '2'}
              newline/>
          )}
        </FormItem>
      </div>
    )
  };

  render() {
    const { loading, formDetail, submitting, editReportFlag, newVendorVisible,
      formMaxHeight, selectCompany } = this.state;
    const { company: { companyOID }, user: { userOID } } = this.props;

    return (
      <div
        className={
          this.classNames({
          "new-corporate-payment-report": true,
          'edit-mode': editReportFlag
          })
        }
        ref='newCorporatePaymentReport'
      >
        <div className='new-corporate-payment-report-box'>
          <div className='form-head'>
          {!editReportFlag && <div className="form-name">{formDetail.formName}</div>}
          {this.renderDescriptionInline()}
          </div>
          <Spin spinning={loading}>
            <Form
              onSubmit={this.handleSave}
              className='new-corporate-payment-report-form'
              style={{height: formMaxHeight}}
            >
              <div className='form-content'>
                {/*关联申请单 & 关联合同*/}
                {this.renderAssociateModule()}

                <div className='form-module'>
                  <h3 className='form-title'>
                    <SVGIcon className="form-title-icon" type="report-info"/>{messages('finance-9.key78')/*单据信息*/}
                  </h3>
                  {this.renderFormItem()}
                </div>

                {/*自选审批人*/}
                {this.renderApproverModule()}
              </div>
              <div className={
                this.classNames({
                  'slide-footer': true,
                  'create-mode': !editReportFlag
                })}
              >
                <Button type="primary" htmlType="submit" loading={submitting} className="button-new">
                  {editReportFlag ? messages('common.save')/*保存*/ : messages('finance-9.key79')/*下一步*/}
                </Button>
                <Button onClick={this.goBack}>{messages('common.cancel')/*取消*/}</Button>
              </div>
            </Form>
            <Modal
              visible={newVendorVisible}
              wrapClassName="new-vendor-modal"
              title={messages('finance-9.key80')/*新增供应商*/}
              cancelText={messages('common.back')/*返回*/}
              width={700}
              onCancel={this.handleCancelNewVendor}
              footer={null}
            >
              <NewVendorForm
                visible={newVendorVisible}
                payeeInfo={{}}
                userOid={userOID}
                companyOid={selectCompany}
                onCancel={this.handleCancelNewVendor}
                onOk={this.handleNewVendorOk}
              />
            </Modal>
          </Spin>
        </div>
      </div>
    )
  }
}

NewExpenseReport.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    loginUser: state.login.loginUser,
    language: state.main.language,
    company: state.login.company,
    tenant: state.login.tenant,
    enableDepCompany: state.setting.enableDepCompany,
    options: state.login.options,
  }
}

NewExpenseReport.propTypes = {
  expenseReport: React.PropTypes.object
};

const WrappedNewExpenseReport = Form.create({
  onValuesChange(props, values) {
    newExpenseReportThis.formItemChange(values);
  },
})(NewExpenseReport);

export default connect(mapStateToProps)(WrappedNewExpenseReport)
